package com.jhd.fuzhou.view.quantitative;

import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.FuzhouApplication;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.service.GradeReportService;
import com.jhd.fuzhou.service.ProcessService;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.SaveSupervisionInspection;
import com.jhd.fuzhou.util.UtilHelper;
import com.jhd.fuzhou.vo.GradeQuestionBankVo;
import com.jhd.fuzhou.vo.GradeQuestionOptionVo;
import com.jhd.fuzhou.vo.JsonForResult;
import com.jhd.fuzhou.vo.PersonInfoVo;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

import static com.jhd.fuzhou.util.StartProcess.completeByAssignUpdate;
import static com.jhd.fuzhou.util.StartProcess.start;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

public class QuantitativeStepFourActivity extends BaseActivity {
    private List<GradeQuestionBankVo> gradeQuestionBankVoList;
    @BindView(R.id.tv_score)
    TextView tv_score;//应得分
    @BindView(R.id.tv_realScore)
    TextView tv_realScore;//实际得分
    @BindView(R.id.tv_quantitative)
    TextView tv_quantitative;//量化分级评分表
    @BindView(R.id.tv_scene_record)
    TextView tv_scene_record;//现场笔录
    @BindView(R.id.tv_health_supervision)
    TextView tv_health_supervision;//监督意见书
    @BindView(R.id.tv_asking_record)
    TextView tv_asking_record;//询问笔录
    @BindView(R.id.tv_notice_record)
    TextView tv_notice_record;//协助调查通知书
    @BindView(R.id.tv_other_record)
    TextView tv_other_record;//其他证件图片、视频
    @BindView(R.id.tv_num_supervision_inspection)
    TextView tv_num_supervision_inspection;//等级
    @BindView(R.id.btn_upload)
    Button btn_upload;//上传
    private Context context = this;
    int score = 0;
    int realScore = 0;
    private List<PersonInfoVo> personInfoVos;
    private boolean isQuantitative = true;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_quantitative_step_four);
    }

    @Override
    protected void processLogic() {
        application.addStepActivity(this);
        onBack();
        getGradeQuestionBankVoList();
        if (!StringUtil.isNullOrEmpty(supervisionInspectionVo.getId())) {
            getTaskApproveLeve1();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        setEnclosureVo();
    }

    private void getGradeQuestionBankVoList() {
        gradeQuestionBankVoList = supervisionInspectionVo.getGradeQuestionBankVoList();
        HashMap<String, List<GradeQuestionBankVo>> gradeQuestionBankVoHashMap = new HashMap<>();
        for (GradeQuestionBankVo gradeQuestionBankVo : gradeQuestionBankVoList) {
            if (gradeQuestionBankVo.getLevel() == 3) {//三级的才能打分
                //1、先判断有没有关键项选的不是合格和是
                for (GradeQuestionOptionVo gradeQuestionOptionVo : gradeQuestionBankVo.getGradeQuestionOptionVoList()) {
                    if ("1".equals(gradeQuestionBankVo.getIsCrux())&&gradeQuestionBankVo.getBankOptionId().equals(gradeQuestionOptionVo.getId()) &&
                            !("合格".equals(gradeQuestionOptionVo.getOptionName()) || "是".equals(gradeQuestionOptionVo.getOptionName()))) {
                        supervisionInspectionVo.setGrade("不予评级");
                        isQuantitative = false;
                        break;
                    }
                }
                //2、根据parentId来进行分组
                if (gradeQuestionBankVoHashMap.containsKey(gradeQuestionBankVo.getParentId())) {
                    List<GradeQuestionBankVo> gradeQuestionBankVoList = gradeQuestionBankVoHashMap.get(gradeQuestionBankVo.getParentId());
                    if (gradeQuestionBankVoList == null) {
                        gradeQuestionBankVoList = new ArrayList<>();
                        gradeQuestionBankVoList.add(gradeQuestionBankVo);
                    } else {
                        gradeQuestionBankVoList.add(gradeQuestionBankVo);
                    }
                } else {
                    List<GradeQuestionBankVo> gradeQuestionBankVoList = new ArrayList<>();
                    gradeQuestionBankVoList.add(gradeQuestionBankVo);
                    gradeQuestionBankVoHashMap.put(gradeQuestionBankVo.getParentId(), gradeQuestionBankVoList);
                }
            }
        }
        //3、分组后将每组的分数进行对比，总扣分如果大于parentScore，就将总扣分赋值为parentScore
        for (List<GradeQuestionBankVo> gradeQuestionBankVoList : gradeQuestionBankVoHashMap.values()) {
            score = score + gradeQuestionBankVoList.get(0).getParentScore();
            int parentScore = gradeQuestionBankVoList.get(0).getParentScore();
            int delScore = 0;
            for (GradeQuestionBankVo gradeQuestionBankVo2 : gradeQuestionBankVoList) {
                delScore = delScore + gradeQuestionBankVo2.getActualScore();
            }
            if (delScore > parentScore) {
                delScore = parentScore;
            }
            realScore = realScore + (parentScore - delScore);
        }
        tv_score.setText("" + score);
        tv_realScore.setText("" +realScore);
        if (isQuantitative) {
            int finalScore = realScore* 100 / score;
            if (finalScore < 60) {
                supervisionInspectionVo.setGrade("不予评级");
            } else if (finalScore >= 60 && finalScore < 70) {
                supervisionInspectionVo.setGrade("C级");
            } else if (finalScore >= 70 && finalScore < 90) {
                supervisionInspectionVo.setGrade("B级");
            } else {
                supervisionInspectionVo.setGrade("A级");
            }
        }
        tv_num_supervision_inspection.setText(supervisionInspectionVo.getGrade());
    }

    @OnClick({R.id.rel_quantitative, R.id.btn_upload, R.id.btn_back})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rel_quantitative:
                Intent intent = new Intent(context, QuantitativeRecordActivity.class);
                intent.putExtra("totalScore", "" + realScore);
                intent.putExtra("shouldScore", "" + score);
                startActivity(intent);
                break;
            case R.id.btn_upload:
                btn_upload.setClickable(false);
                upload();
                break;
            case R.id.btn_back:
                onBackPressed();
                break;
        }
    }

    /*上传表单*/
    public void upload() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        GradeReportService vs = retrofit.create(GradeReportService.class);
        Call<JsonForResult> jsonForResultCall = vs.saveGradeReportMst(application.getAccessToken(), SaveSupervisionInspection.saveQuantitative(supervisionInspectionVo, personInfoVos, application,score,realScore));
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (StringUtil.isNullOrEmpty(supervisionInspectionVo.getId())) {
                            start(application, jsonForResult.getData().toString(), "量化分级", context);
                        } else {
                            completeByAssignUpdate(application, personInfoVos.get(0).getUserName(), supervisionInspectionVo.getTaskId(), "", null, supervisionInspectionVo.getId(), "未审核", "修改成功", context);
                        }
                    } else {
                        CustomToast.showText(context, "添加量化分级失败！", 3000, 0, 0).show();
                        btn_upload.setClickable(true);
                    }
                } catch (Exception e) {
                    UtilHelper.alertMsg(context, "错误", e.getMessage());
                    btn_upload.setClickable(true);
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "上传失败!";
                UtilHelper.alertMsg(context, "错误", msg);
                btn_upload.setClickable(true);
            }
        });
    }

    public void getTaskApproveLeve1() {
        Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API());//URL的头
        ProcessService vs = retrofit.create(ProcessService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("username", application.getName()).addParam("userId", application.getUserId());
        Call<JsonForResult> jsonForResultCall = vs.getTaskApproveLeve1(application.getAccessToken(), params);//调用接口获取json返回
        jsonForResultCall.enqueue(new Callback<JsonForResult>() {
            @Override
            public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
                try {
                    JsonForResult jsonForResult = (JsonForResult) response.body();
                    if (jsonForResult != null && jsonForResult.isSuccess()) {
                        if (jsonForResult.getData() != null) {
                            personInfoVos = JSON.parseArray(jsonForResult.getData().toString(), PersonInfoVo.class);
                        }
                    } else {
                        UtilHelper.alertMsg(context, "错误", jsonForResult.getMessage());
                    }
                } catch (Exception e) {
                    CustomToast.showText(context, e.getLocalizedMessage(), 3000, 0, 0).show();
                }
            }

            @Override
            public void onFailure(Call<JsonForResult> call, Throwable t) {
                String msg = "网络异常!";
                if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
                UtilHelper.alertMsg(context, "错误", msg);
            }
        });
    }

    private void setEnclosureVo() {
        List<SuperviseEnclosureVo> superviseEnclosureVoList = supervisionInspectionVo.getSuperviseEnclosureVoList();
        if (superviseEnclosureVoList != null) {
            for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                if (superviseEnclosureVo.getEnclosureName().equals("现场笔录")) {
                    tv_scene_record.setText("已制作");
                    tv_scene_record.setTextColor(getResources().getColor(R.color.black));
                } else if (superviseEnclosureVo.getEnclosureName().equals("监督意见书")) {
                    tv_health_supervision.setText("已制作");
                    tv_health_supervision.setTextColor(getResources().getColor(R.color.black));
                } else if (superviseEnclosureVo.getEnclosureName().equals("询问笔录")) {
                    tv_asking_record.setText("已制作");
                    tv_asking_record.setTextColor(getResources().getColor(R.color.black));
                } else if (superviseEnclosureVo.getEnclosureName().equals("协助调查通知书")) {
                    tv_notice_record.setText("已制作");
                    tv_notice_record.setTextColor(getResources().getColor(R.color.black));
                } else if (superviseEnclosureVo.getEnclosureName().equals("其他证件图片、视频")) {
                    tv_other_record.setText("已制作");
                    tv_other_record.setTextColor(getResources().getColor(R.color.black));
                } else if (superviseEnclosureVo.getEnclosureName().equals("量化分级评分表")) {
                    tv_quantitative.setText("已制作");
                    tv_quantitative.setTextColor(getResources().getColor(R.color.black));
                }
            }
        }
    }
}